package com.study;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Set;

public class ServletWebApplicationInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        try {
            Context cxt = new InitialContext();
            DataSource derbyDataSource = (DataSource) cxt.lookup("java:comp/env/jdbc/DemoDataSource");
            Connection connection = derbyDataSource.getConnection();
            System.out.println("成功获取数据库连接...");
            initData(connection);
        } catch (NamingException | SQLException e) {
            System.out.println(e);
        }
    }

    /**
     * 准备基础数据
     * @param connection connection
     */
    private void initData(Connection connection) throws SQLException {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("DROP TABLE HELLO");
            preparedStatement.executeUpdate();
            System.out.println("清除已经存在的数据...");
        } catch (SQLException e) {
            System.out.println(e);
        }
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("CREATE TABLE HELLO (ID INT, CONTENT VARCHAR(255))");
            preparedStatement.executeUpdate();
            System.out.println("基础表创建完成...");
        } catch (SQLException e) {
            System.out.println(e);
        }
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO HELLO VALUES(1,'张三')");
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement("INSERT INTO HELLO VALUES(2,'李四')");
            preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement("INSERT INTO HELLO VALUES(3,'王五')");
            preparedStatement.executeUpdate();
            connection.commit();
            System.out.println("基础数据准备完成...");
        } catch (SQLException e) {
            connection.rollback();
        }
        connection.close();
    }
}
